const User =  require('../models/System/User')
const jwt = require('jsonwebtoken')
const assert = require('http-assert')
const https = require('https')
// 用户登录校验&获取用户登录IP地址
module.exports = options => async (req,res,next)=>{
    const { userName,password,imgCode } = req.body
        // img_code 获取传递的图片验证码 ,如果不相等，验证码错误S
        assert(imgCode.toLocaleUpperCase() === req.session.imgLoginCode, 422, '验证码错误')
        // 1.根据用户名找用户
        const isUser = await User.findOne({userName}).select('+password')
        assert(isUser, 422, '用户不存在')
        // 2.校验密码
        const isValid = require('bcrypt').compareSync(password, isUser.password)
        assert(isValid, 422, '密码错误')
        // 3.返回token
        const token = jwt.sign({id:isUser._id},req.app.get('secret'))
        req.token = token
    // 获取用户登录Ip,百度地图api
    // 获取地址 https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //HTTPS协议
    let ip = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
    let option = {
        hostname:"api.map.baidu.com",//接口域名
        path:`/location/ip?ip=${ip}&ak=IjlQyeDxGb3QGxhcD7Wsik6UISYieSLt`,//path格式
        headers:{//设置请求头
            "Content-Type":"application/json; charset=utf-8",
            "Authorization": "APPCODE 4390f21526a64f3c99bca6260b9f295d",
        }
    };
    // ip信息
    const ipInfo = {}
    const post_req = await https.request(option, async (Res)=>{

        Res.setEncoding('utf8');
        if(Res.statusCode===200){//若http状态码为200则请求成功
            Res.on('data',async (data) => {
                if(JSON.parse(data).status === 0){
                    const {province , city} = JSON.parse(data).content.address_detail
                    ipInfo.userSite= province  + " " + city
                    ipInfo.userCity= city
                    ipInfo.userIp = ip
                }else{
                    ipInfo.userSite= '内网IP'
                    ipInfo.userCity= ''
                    ipInfo.userIp = ip
                }
                await User.findByIdAndUpdate(isUser._id,ipInfo)
                req.user = await User.findById(isUser._id)
                await next()
            });
        }else{
            ipInfo.userSite= '内网IP'
            ipInfo.userCity= ''
            ipInfo.userIp = ip
            await User.findByIdAndUpdate(isUser._id,ipInfo)
            req.user = await User.findById(isUser._id)
            await next()
        }
    })

    post_req.end();
}